﻿using AutoMapper;
using B.S.GridManager.Api.Write.Application.Command.PhsicalGrid;
using B.S.GridManager.ErrorCode;
using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using MediatR;

namespace B.S.GridManager.Api.Write.Application.CommandHandler.PhsicalGrid
{
    /// <summary>
    /// 更新物理网格中介者处理类
    /// </summary>
    public class UpdatePhsicalGridHandler : IRequestHandler<UpdatePhsicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicalGridModel> physicalRepo;//物理网格仓储
        private readonly ILogger<UpdatePhsicalGridHandler> logger;//日志组件
        private readonly IMapper mapper;//automap组件

        /// <summary>
        /// 通过构造函数注入需要的对象
        /// </summary>
        /// <param name="physicalRepo">物理网格仓储</param>
        /// <param name="logger">日志组件</param>
        /// <param name="mapper">automap组件</param>
        public UpdatePhsicalGridHandler(IBaseRepository<PhysicalGridModel> physicalRepo,ILogger<UpdatePhsicalGridHandler> logger,IMapper mapper)
        {
            this.physicalRepo = physicalRepo;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 更新物理网格的处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdatePhsicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var entity = physicalRepo.GetModel(request.Id);//通过id查找要更新的物理网格
            if (entity == null)
            { //entity为空,没有找到要更新的物理网格
                result.Code = ApiEnums.Fail;
                result.Msg = "您要更新的物理网格不存在";
                //result.Data = 
                return Task.FromResult(result); //直接返回
            }


            entity= mapper.Map(request, entity);//在更新之前,把request的值全部映射到entity

            int r = physicalRepo.Update(entity);//更新entity

            if (r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "更新成功!";
                result.Data = r;
            }
            else
            {
                result.Code = ApiEnums.Fail;
                result.Msg = "更新失败!";
                result.Data = r;
            }

            return Task.FromResult(result);
        }
    }
}
